<?php
include_once ("include/includes.inc");
include_once ("include/settings.inc");
include_once ("$parser_path/excelparser.php");
if ( $_POST['step'] == 1 ) {	
	// Uploading file

	$excel_file = $_FILES['excel_file'];
	if( $excel_file )
		$excel_file = $_FILES['excel_file']['tmp_name'];

	if( $excel_file == '' ) fatal("No file uploaded");
	
	move_uploaded_file( $excel_file, 'upload/' . $_FILES['excel_file']['name']);	
	$excel_file = 'upload/' . $_FILES['excel_file']['name'];
	
	
	$fh = @fopen ($excel_file,'rb');
	if( !$fh ) fatal("No file uploaded");
	if( filesize($excel_file)==0 ) fatal("No file uploaded");

	$fc = fread( $fh, filesize($excel_file) );
	@fclose($fh);
	if( strlen($fc) < filesize($excel_file) )
		fatal("Cannot read file");	
	
	
	// Check excel file
	
	$exc = new ExcelFileParser ();
	$res = $exc->ParseFromString($fc);
	
	switch ($res) {
		case 0: break;
		case 1: fatal("Can't open file");
		case 2: fatal("File too small to be an Excel file");
		case 3: fatal("Error reading file header");
		case 4: fatal("Error reading file");
		case 5: fatal("This is not an Excel file or file stored in Excel < 5.0");
		case 6: fatal("File corrupted");
		case 7: fatal("No Excel data found in file");
		case 8: fatal("Unsupported file version");
		default:
			fatal("Unknown error");
	}
	
		
	// Pricessing worksheets
	
	$ws_number = count($exc->worksheet['name']);
	if( $ws_number < 1 ){
		fatal("No worksheets in Excel file.");
	}	
	
	//$ws_number = 1; // Setting to process only the first worksheet
	
	for ($ws_n = 0; $ws_n < $ws_number; $ws_n++) {
		
		$ws = $exc -> worksheet['data'][$ws_n]; // Get worksheet data
			
		if ( !$exc->worksheet['unicode'][$ws_n] )
			$db_table = $ws_name = $exc -> worksheet['name'][$ws_n];
		else 	{
			$ws_name = uc2html( $exc -> worksheet['name'][$ws_n] );
			$db_table = convertUnicodeString ( $exc -> worksheet['name'][$ws_n] );
		}
		
		//echo "<div align=\"center\">Worksheet: <b>$ws_name</b></div><br>";	
		
		$max_row = $ws['max_row'];
		$max_col = $ws['max_col'];
		$data = $ws['cell'];
		
		$data_array=array();
		$campaign_object=array();
		$addttext_object=array();		
		$array_data_sheet=array();
		$row_data=array();
		$count_row=count($data);		
		foreach( $data as $i => $row ) { // Output data and prepare SQL instructions
			if ( $i == 0 && $_POST['useheaders'] )
				continue;							
			for ( $j = 0; $j <= $ws['max_col']; $j++ ) {							
					$cell = addslashes(get($exc,$row[$j]));
					//echo "<td>$cell</td>";
					if($j%2==0){
						$row_data[$i][]=$cell;
					}						
			}			
			$i++;
		}				
		$infoHeader_array=array();
		$addText_array=array();
		$destinationURL_array=array();
		$keyword_array=array();
		$des=false;
		$keyword=false;
		$addtext=true;
		$group_add=0;
		$index_array=0;
		// parse data tyo array object 
		
		$real_colum=$ws['max_col']-$ws['max_col']/2;			
		for ($t=0;$t<500;$t++){
			$val=$t%2;
			if($t<15){
				if($val)
				{
					$infoHeader_array[]=$row_data[$t];
				}
			}else{				
				for ( $k = 0; $k <=$real_colum; $k++ ) {
					$destination_url_header=$row_data[$t][$k];
					if($destination_url_header!='')
						 break;
				}
				if(!empty($destination_url_header)){
					if($destination_url_header !='Destination URL'){						
						if($addtext){							
							$addText_array[$index_array][]=$row_data[$t];
							$group_add++;
							$index_array=$group_add/4;							
						}elseif($des){
							if($destination_url_header !='Keywords'){
								$destinationURL_array[]=$row_data[$t];	
							}else{
								$des=false;							
							}
							
						}else{
							$keyword_array[]=$row_data[$t];
						}							
					}else{
						$des=true;
						$addtext=false;											
					}
				}								
							
			}
		}
		// convert data array data  to object data
		$addcopy_array=array();		
		for($i=0;$i<count($addText_array);$i++){
			for ( $j = 0; $j <= $real_colum; $j++ ) {
				$addcopy_array[$i][]=array(
										"headline"=>$addText_array[$i][0][$j],
										"description_line_1"=>$addText_array[$i][1][$j],
										"description_line_2"=>$addText_array[$i][2][$j],
										"display_url"=>$addText_array[$i][3][$j],
										"destination_url"=>$destinationURL_array[$i][$j]
									);
			}			
		}		
			
		//echo "<pre>"; print_r($destinationURL_array); echo "</pre>";
		//echo "<pre>"; print_r( $addText_array); echo "</pre>";	
		
		for ( $k = 0; $k <= $real_colum; $k++ ) {
			$campaign_object[$k]['company_name']= $infoHeader_array[0][$k];
			$campaign_object[$k]['campaign_name']=$infoHeader_array[1][$k];
			$campaign_object[$k]['ad_group']=$infoHeader_array[2][$k];
			$campaign_object[$k]['search_engines']=$infoHeader_array[3][$k];
			$campaign_object[$k]['markets']=$infoHeader_array[4][$k];
			$campaign_object[$k]['language_targeting']=$infoHeader_array[5][$k];
			$campaign_object[$k]['duration']=$infoHeader_array[6][$k];	
			$campaign_object[$k]['add_text']=getAdCopy($addcopy_array,$k);						
			$campaign_object[$k]['key_words']=getAdKeywords($keyword_array,$k);						
		}
		
	}	
	//echo "<pre>"; print_r($campaign_object); echo "</pre>";	
	//exit;		
	$data_to_csv[]= array('Campaign','Campaign Daily Budget','Languages','Geo Targeting','Proximity Targets','Ad Schedule', 'Ad Group','Max CPC','Display Network Max CPC','Placement Max CPC',
	'Max CPM','CPA Bid','Keyword','Keyword type','First Page CPC','Quality Score','Headline','Description Line 1','Description Line 2','Display URL','Destination URL','Campaign Status','AdGroup Status','Creative Status',
	'Keyword Status','Suggested Changes','Comment','Impressions','Clicks','CTR','Avg CPC','Avg CPM','Cost','Avg Position','Conversions (1-per-click)','Conversion Rate (1-per-click)','Cost/Conversion (1-per-click)','Conversions (many-per-click)',
	'Conversion Rate (many-per-click)','Cost/Conversion (many-per-click)');
	
	$result_array_t=array();	
	foreach($campaign_object as $item){		
		$result_array_t=prepareObjectData2Array($item);
		foreach($result_array_t as $item1){
			array_push($data_to_csv,$item1);
		}	
	}	
	$content_from_csv= array_to_csv($data_to_csv);			
	//echo "<pre>"; print_r($content_from_csv); echo "</pre>";	
	
	$content_from_csv=str_replace("|","\t",$content_from_csv);
	
	//echo "<pre>"; print_r($content_from_csv); echo "</pre>";	
	//exit;
	
	$mime = 'text/csv, application/csv, application/excel, application/vnd.ms-excel, application/vnd.msexcel, text/anytext' ;
	$encoding = 'utf-8';
	header('Pragma: public');
	header('Expires: 0');
	header('Content-Description: File Transfer');
	header('Content-Type: application/csv,utf-8');
	header('Content-Transfer-Encoding: ' . $encoding);
	header('Content-Disposition: attachment; filename=' . date("Y-m-d") .'_adwords.csv');
	header('Content-Length: ' . strlen($content_from_csv));			
	ob_start();
	$content_from_csv = chr(255).chr(254).mb_convert_encoding($content_from_csv, "UTF-16LE", "UTF-8");
	echo $content_from_csv;
	ob_end_flush();
}
?>